package com.itheima.controller;

import com.itheima.anno.Log;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result list() {
        List<Dept> deptList = deptService.list();
        return Result.success(deptList);
    }

    @Log
    @PostMapping
    public Result addDept(String deptName) {
        //先查询添加的部门是否存在，如果存在就提示用户
        boolean isExit = deptService.findDeptName(deptName);
        if(isExit) {
            return Result.error("该部门已存在");
        }else {
            Dept dept = new Dept();
            dept.setName(deptName);
            deptService.add(dept);
            return Result.success();
        }
    }
    @Log
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        deptService.delete(id);
        return Result.success();
    }
    @PutMapping
    public Result update(Integer id,String deptName) {
        //先把要更新的部门查询出来
        Dept dept = deptService.findById(id);
        if(dept == null) {
            return Result.error("部门不存在");
        }
        dept.setName(deptName);
        dept.setUpdateTime(LocalDateTime.now());
        deptService.update(dept);
        return Result.success();
    }
}
